package com.yunc.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.controller.CommonController;
import com.yunc.common.aspect.BaseLog;
import com.yunc.common.utils.BaseConstant;
import com.yunc.common.utils.R;
import com.yunc.modules.sys.entity.SysMenu;
import com.yunc.modules.sys.entity.SysRole;
import com.yunc.modules.sys.service.ISysMenuService;
import com.yunc.modules.sys.service.ISysRoleService;
import com.yunc.modules.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 菜单
 *
 * @author taocongcong
 * @create 2017-12-15 13:50
 */
@RestController
@RequestMapping("sysMenu")
public class SysMenuController extends CommonController {

    private static final Logger logger = LogManager.getLogger(SysMenuController.class);

    @Autowired
    private ISysMenuService sysMenuService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserService sysUserService;

    @BaseLog("菜单管理")
    @GetMapping("/list")
    public R list(SysMenu sysMenu){
        QueryWrapper<SysMenu> ew = new QueryWrapper<SysMenu>()
                .orderByAsc("order_num");
        if (StringUtils.isNotEmpty(sysMenu.getName())) {
            ew.like("name", sysMenu.getName());
        }
        List<SysMenu> sysMenuList = sysMenuService.list(ew);
        logger.info("在" + new Date() + "查询所有菜单");
        return R.ok().put("data", sysMenuList);
    }

    @BaseLog("菜单管理")
    @GetMapping("/list/{roleId}")
    public R roleMenuTreeData(@PathVariable Long roleId, SysMenu sysMenu){
        List<Map<String, Object>> tree = sysMenuService.roleMenuTreeData(sysMenu, roleId);
        return R.ok().put("tree", tree);
    }

    @GetMapping("queryMenuList")
    public List<SysMenu> queryMenuList(){
        // 下拉树
        List<SysMenu> sysMenuList = sysMenuService.queryUserMenuList();
        return sysMenuList;
    }

    @GetMapping("/listAuth")
    public R queryMenuTreeForAuth(Long roleId, SysMenu sysMenu){
        SysRole sysRole = sysRoleService.getById(roleId);
        QueryWrapper<SysMenu> ew = new QueryWrapper<>(sysMenu);
        ew.orderByAsc("order_num");
        List<SysMenu> sysMenuList = sysMenuService.list(ew);
        List<Long> menuIdList = new ArrayList<>();
        if (roleId != null) {
            List<String> menuIdStrList = sysUserService.queryMenuIdByRoleId(roleId);
            if (menuIdStrList != null && menuIdStrList.size() > 0) {
                for (String menuId : menuIdStrList) {
                    menuIdList.add(Long.parseLong(menuId));
                }
            }
        }
        return R.ok().put("sysRole", sysRole).put("sysMenuList", sysMenuList).put("menuIdList", menuIdList);
    }

    @GetMapping("queryUserMenuList")
    public R queryUserMenuList(){
        // 根据角色查询
        List<SysMenu> sysMenuList = sysMenuService.queryUserMenuList(getUserId());
        Set<String> permissions = sysUserService.queryUserMenuPermsList(getUserId());
        return R.ok().put("data", sysMenuList).put("permissions", permissions);
    }

    @GetMapping("/page")
    public Page<SysMenu> page(Page<SysMenu> page, SysMenu sysMenu){
        sysMenuService.page(page, new QueryWrapper<>(sysMenu));
        return page;
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    public R info(@PathVariable String menuId){
        SysMenu menu = sysMenuService.getById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @BaseLog("菜单管理")
    @PostMapping("/save")
    @RequiresPermissions("sys:menu:save")
    @CacheEvict(value={"userMenus","userMenuAll"}, allEntries=true)
    public R save(@RequestBody SysMenu menu){
        menu.setRemoveTag(BaseConstant.REMOVE_N);
        menu.setCreateTime(new Date());
        boolean flag = sysMenuService.save(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @BaseLog("菜单管理")
    @PutMapping(value = "/update")
    @RequiresPermissions("sys:menu:update")
    @CacheEvict(value={"userMenus","userMenuAll"}, allEntries=true)
    public R update(@RequestBody SysMenu menu){
        boolean flag = sysMenuService.updateById(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{menuId}")
    @RequiresPermissions("sys:menu:delete")
    public R delete(@PathVariable Long menuId){
        // 查询是否存在子菜单
        // List<SysMenu> sysMenuList = sysMenuService.queryListParentId(menuId, null);
        SysMenu record = new SysMenu();
        record.setParentId(menuId);
        QueryWrapper<SysMenu> ew = new QueryWrapper<>(record);
        int count = sysMenuService.count(ew);
        if (count > 0) {
            return R.error("存在子菜单，不允许删除");
        }
        SysMenu menu = sysMenuService.getById(menuId);
        menu.setRemoveTag(BaseConstant.REMOVE_Y);
        // boolean flag = sysMenuService.deleteById(menuId);
        boolean flag = sysMenuService.updateById(menu);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}
